import { View, Text, Image, Button } from "@tarojs/components";
import Taro, { useLoad } from "@tarojs/taro";
import "./index.scss";
import { useState } from "react";
import { useDispatch } from "react-redux";
import { addCartList } from "../../store/cart";
import { AtNavBar } from "taro-ui";

export default function Detail() {
  const [item, setItem] = useState({});
  const dispatch = useDispatch();
  const fetchItem = async (id) => {
    const resp = await Taro.request({
      url: "http://localhost:3000/list/" + id,
    });
    setItem(resp.data);
  };
  const handleClick = () => {
    Taro.navigateBack();
  };

  useLoad(() => {
    const params = Taro.getCurrentInstance().router.params;
    fetchItem(params.id);
  });

  return (
    <View className="detail">
      {/* 头部 */}
      {process.env.TARO_ENV === "h5" && (
        <AtNavBar
          onClickLeftIcon={handleClick}
          color="#000"
          title="详情"
          leftIconType="chevron-left"
        />
      )}
      {/* 商品详情信息 */}
      <Image src={item.image} style={{ width: "100%", height: 200 }}></Image>
      <View>{item.title}</View>
      <View>{item.desc}</View>
      <View>¥：{item.price}</View>
      {/* 底部加入购物车 */}
      <Button
        type="primary"
        onClick={() =>
          {
            Taro.showToast({
              title: '添加成功'
            })
            dispatch(
              addCartList({
                ...item,
                count: 1,
                state: true,
              })
            )
          }
        }
      >
        加入购物车
      </Button>
    </View>
  );
}
